package com.ivanceras.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.ivanceras.client.widgets.AWindow;
import com.ivanceras.client.widgets.DataImporterUI;
import com.ivanceras.client.widgets.XmlReaderUI;
import com.ivanceras.shared.bo.Ad_window;

public class Ivanceras implements EntryPoint {
	private final DataServiceAsync dataService = GWT
	.create(DataService.class);

	HTMLPanel mainPanel = new HTMLPanel("");
	Button importLink = new Button("Import Module");
	Button sendButton = new Button("Windows");
	Button xmlReader = new Button("XML Reader");
	

	public void onModuleLoad() {
		RootPanel.get().add(importLink);
		RootPanel.get().add(sendButton);
		RootPanel.get().add(xmlReader);
		RootPanel.get().add(mainPanel);
		importLink.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				DataImporterUI importer = new DataImporterUI();
				mainPanel.clear();
				mainPanel.add(importer);
			}
		});
		sendButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				retrieveWindows();
			}
		});
		xmlReader.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {
				mainPanel.clear();
				XmlReaderUI reader = new XmlReaderUI();
				mainPanel.add(reader);
			}
			
		});
	}
	
	void retrieveWindows(){
		System.out.println("Retrieving window list: ");
		dataService.retrieveWindowList(new AsyncCallback<Ad_window[]>() {

			@Override
			public void onFailure(Throwable caught) {
				
			}

			@Override
			public void onSuccess(Ad_window[] result) {
				RootPanel panel = RootPanel.get();
				for(final Ad_window win : result){
					Anchor a = new Anchor();
					a.setHTML(win.getName());
					a.setHref("#"+win.getAd_window_id());
					a.addClickHandler(new ClickHandler() {
						
						@Override
						public void onClick(ClickEvent event) {
							showWindow(win);
						}
					});
					panel.add(a);
					panel.add(new HTML("<br/>"));
				}
			}
		
		});
	}

	private void showWindow(Ad_window win) {
		AWindow a_win =  new AWindow(win);
		mainPanel.clear();
		mainPanel.add(a_win);
	}

}
